package com.sina.common.okhttp;

import android.app.Activity;
import android.text.TextUtils;

import com.sina.common.okhttp.bean.HttpResult;
import com.sina.common.util.GsonUtils;
import com.sina.common.util.SPUtils;
import com.sina.common.util.ToastUtils;
import com.sina.common.util.bean.UserData;
import com.sina.common.value.StaticValue;



import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 请求对象获取
 */
@SuppressWarnings({"unused", "WeakerAccess"})
public class OkHttpRequest {

    /**
     * JSON格式
     */
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private OkHttpRequest() {

    }

    /**
     * get请求方式
     */
    public static Request getRequest(String url, String actionUrl) {
        return getRequest(url, actionUrl, null, null);
    }

    /**
     * get请求方式
     */
    public static Request getRequest(String url, String actionUrl, Map<String, String> params) {
        String urlFormat = getUrlFormat(url, actionUrl);
        StringBuilder tempParams = new StringBuilder();
        //处理参数
        int pos = 0;
        Map<String, String> parameter = getParameter();
        parameter.putAll(params);
        for (String key : parameter.keySet()) {
            if (pos > 0) {
                tempParams.append("&");
            }
            //对参数进行URLEncoder
            try {
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(parameter.get(key), "utf-8")));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            pos++;
        }
        urlFormat += tempParams.toString();

        if (urlFormat.endsWith("/")) {
            urlFormat = urlFormat.substring(0, urlFormat.length() - 1);
        }
        Request.Builder requestBuilder = new Request.Builder().url(urlFormat).get();
        setHeader(requestBuilder);
        return requestBuilder.build();

    }

    /**
     * get请求方式
     */
    public static Request getRequest(String url, String actionUrl, String key, String value) {
        Map<String, String> map = new HashMap<>();

        if (!TextUtils.isEmpty(key)) {
            map.put(key, value);
        }
        return getRequest(url, actionUrl, map);
    }

    /**
     * 请注意  "" 与 null 是不同的
     *
     * @param url       url
     * @param actionUrl action
     * @return 返回值
     */
    private static String getUrlFormat(String url, String actionUrl) {
        String formatUrl;
        if (actionUrl == null) {
            if (url.endsWith("/")) {
                formatUrl = url + "?";
            } else {
                formatUrl = url + "/?";
            }
        } else {
            if (url.endsWith("/?")) {
                formatUrl = url + actionUrl + "?";
            } else {
                formatUrl = url + "/" + actionUrl + "?";
            }
        }
        return formatUrl;
    }

//    /**
//     * post请求方式
//     */
//    public static Request postRequest(String url) {
//        FormBody.Builder formBodyBuilder = new FormBody.Builder();
//        setParameter(formBodyBuilder);
//        RequestBody requestBody = formBodyBuilder.build();
//        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
//        setHeader(requestBuilder);
//        return requestBuilder.build();
//    }

    /**
     * post请求方式
     */
    public static Request postRequest(String url, String json) {
        if (json != null && !TextUtils.isEmpty(json.trim())) {
            json = json.trim();
            String params = GsonUtils.toJson(getParameter());
            params = params.substring(0, params.length() - 1);
            if (json.startsWith("{")) {
                json = params + "," + json.substring(1, json.length());
            } else if (json.startsWith("[")) {
                json = params + "," + json + "}";
            }
        } else {
            json = GsonUtils.toJson(getParameter());
        }
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
        setHeader(requestBuilder);
        return requestBuilder.build();
    }

    /**
     * post请求方式
     */
    public static Request postRequestHashMap(String url, String json) {
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
        setHeader(requestBuilder);
        return requestBuilder.build();
    }


    /**
     * post请求方式
     */
    public static Request postRequest(String url, String name, File file) {
        return postRequest(url, name, file, null);
    }

    /**
     * post请求方式
     */
    public static Request postRequest(String url, String name, File file, Map<String, String> params) {
        RequestBody fileBody = RequestBody.create(MultipartBody.FORM, file);
        MultipartBody.Builder builder = new MultipartBody.Builder().addFormDataPart(name, file.getName(), fileBody);
        if (params != null) {
            for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
                builder.addFormDataPart(stringStringEntry.getKey(), stringStringEntry.getValue() != null ? stringStringEntry.getValue() : "");
            }
        }
        setParameter(builder);
        RequestBody requestBody = builder.build();
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
        setHeader(requestBuilder);
        return requestBuilder.build();
    }

    /**
     * post请求方式
     */
    public static Request postRequest(String url, String name, byte[] bytes) {
        return postRequest(url, name, bytes, null);
    }

    /**
     * post请求方式
     */
    public static Request postRequest(String url, String name, byte[] bytes, Map<String, String> params) {
        RequestBody byteBody = RequestBody.create(MultipartBody.FORM, bytes);
        //创建RequestBody
        MultipartBody.Builder builder = new MultipartBody.Builder().addFormDataPart(name, "", byteBody);
        if (params != null) {
            for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
                builder.addFormDataPart(stringStringEntry.getKey(), stringStringEntry.getValue() != null ? stringStringEntry.getValue() : "");
            }
        }
        setParameter(builder);
        RequestBody requestBody = builder.build();
        //创建Request
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
        setHeader(requestBuilder);
        return requestBuilder.build();
    }

    /**
     * post请求方式
     */
    public static Request postRequest(String url, String key, String value) {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        setParameter(formBodyBuilder);
        if (!TextUtils.isEmpty(key)) {
            formBodyBuilder.add(key, value);
        }
        RequestBody requestBody = formBodyBuilder.build();
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
        setHeader(requestBuilder);
        return requestBuilder.build();
    }


    /**
     * post请求方式
     */
    public static Request postTableRequest(String url, Map<String, String> params) {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        setParameter(formBodyBuilder);
        if (params != null) {
            for (String s : params.keySet()) {
                formBodyBuilder.add(s, params.get(s));
            }
        }
        RequestBody requestBody = formBodyBuilder.build();
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
        setHeader(requestBuilder);
        return requestBuilder.build();
    }


    /**
     * 更新请求头
     *
     * @param builder 操作体
     */
    private static void setHeader(Request.Builder builder) {
        //        builder.addHeader(key, value);
        //        builder.header(key, value);
        UserData userData = (UserData) SPUtils.readObj(StaticValue.getApp(), "UserData");
        String token = "";
        if(userData != null) {
            token = userData.getToken();
        }
        builder.addHeader("token", token);
        builder.addHeader("User-Agent", StaticValue.getUserAgent());
    }

    /**
     * 默认参数请存入该map
     *
     * @return 默认参数集
     */
    private static Map<String, String> getParameter() {
        Map<String, String> map = new HashMap<>();

//        String appInfo = GetPhoneMessageUtils.getAppInfo();
//
//        String channel = GetPhoneMessageUtils.getChannel();
//
//        String deviceId = GetPhoneMessageUtils.getIMEI(StaticValue.getApp());
//
//        String deviceIp = GetPhoneMessageUtils.getIPAddress(StaticValue.getApp());
//
//        String deviceMac = GetPhoneMessageUtils.getMac();
//
//        String equipSys = GetPhoneMessageUtils.getSDK();
//
//        String imei = GetPhoneMessageUtils.getIMEI(StaticValue.getApp());
//
//        String isRoot = GetPhoneMessageUtils.getHasRoot() ? "1" : "0";
//
//        String lat = StaticValue.getLat();
//
//        String lon = StaticValue.getLon();
//
//        String phoneModel = GetPhoneMessageUtils.getBrand() + " " + GetPhoneMessageUtils.getModel();
//
//        String phoneOs = GetPhoneMessageUtils.getPhoneType();
//
//        // APP信息(应用名-版本号)
//        map.put("appInfo", appInfo);
//        // 渠道
//        map.put("channel", channel != null ? channel : "");
//        // 设备号
//        map.put("deviceId", deviceId != null ? deviceId : "");
//        // 设备IP
//        map.put("deviceIp", deviceIp != null ? deviceIp : "");
//        // 请求设备MAC
//        map.put("deviceMac", deviceMac != null ? deviceMac : "");
//        // 操作系统
//        map.put("equipSys", equipSys != null ? equipSys : "");
//        // imei
//        map.put("imei", imei != null ? imei : "");
//        // 是否root(安卓系统专用)(0未root1已root)
//        map.put("isRoot", isRoot);
//        // 纬度
//        map.put("lat", lat != null ? lat : "");
//        // 经度
//        map.put("lon", lon != null ? lon : "");
//        // 手机型号
//        map.put("phoneModel", phoneModel);
//        // 手机系统(ios or android)
//        map.put("phoneOs", phoneOs);
        return map;
    }

    private static void setParameter(MultipartBody.Builder builder) {
        Map<String, String> parameter = getParameter();
        for (Map.Entry<String, String> stringStringEntry : parameter.entrySet()) {
            builder.addFormDataPart(stringStringEntry.getKey(), stringStringEntry.getValue() == null ? "" : stringStringEntry.getValue());
        }
    }

    private static void setParameter(FormBody.Builder builder) {
        Map<String, String> parameter = getParameter();
        for (Map.Entry<String, String> stringStringEntry : parameter.entrySet()) {
            builder.add(stringStringEntry.getKey(), stringStringEntry.getValue() == null ? "" : stringStringEntry.getValue());
        }
    }

    /**
     * 该方法是为了兼容之前的 readResult 方法，后期都要替换掉的。
     *
     * @param activity 上下文
     * @param result   网络请求结果
     * @return 解析出的 data字符串
     */
    public static String readResult(Activity activity, String result) {
        return readResult(activity, result, String.class);
    }

    public static <T> T readResult(Activity activity, String result, Class<T> clazz) {

        HttpResult baseBean = GsonUtils.fromJson(result, HttpResult.class);
        if (baseBean.getResult() == null) {
            if ((baseBean.getCode() == null || baseBean.getCode() != 0) && !TextUtils.isEmpty(baseBean.getMessage()) && !baseBean.getMessage().equals("null")) {
                ToastUtils.showToast(baseBean.getMessage());
            }
            return null;
        } else {
            if (baseBean.getResult() instanceof String) {
                return (T) baseBean.getResult();
            } else {
                String json = GsonUtils.toJson(baseBean.getResult());
                if (clazz.getName().equals("java.lang.String") && clazz.isAssignableFrom(String.class)) {
                    return (T) json;
                } else {
                    return GsonUtils.fromJson(json, clazz);
                }
            }
        }

    }

    public static <T> List<T> checkResultList(Activity activity, String result, Class<T> clazz) {
        HttpResult baseBean = GsonUtils.fromJson(result, HttpResult.class);
        if (baseBean == null) {
            ToastUtils.showToast("网络请求错误，请稍后再试或者联系客服人员。");
            return null;
        }
        if ((baseBean.getCode() == null || baseBean.getCode() != 0) && !TextUtils.isEmpty(baseBean.getMessage()) && !baseBean.getMessage().equals("null")) {
            ToastUtils.showToast(baseBean.getMessage());
            return null;
        } else {
            if (baseBean.getResult() == null) {
                return null;
            } else {
                String json = GsonUtils.toJson(baseBean.getResult());
                T t;
                List<T> list = new ArrayList<>();
                try {
                    JSONArray jsonArray = new JSONArray(json);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        t = GsonUtils.fromJson(jsonArray.getString(i), clazz);
                        list.add(t);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return list;
            }
        }
    }
}
